package com.yuxl.common.auth.service;

import com.yuxl.common.auth.entity.AuthPermission;
import com.yuxl.common.auth.entity.AuthRolePermission;
import com.yuxl.common.auth.repository.AuthRolePermissionRepository;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author yuxl
 */
@Slf4j
@Service
public class AuthRolePermissionService {
    @Resource
    private AuthRolePermissionRepository authRolePermissionRepository;

    public Flux<AuthPermission> findByRoleMark(String roleMark) {
        return authRolePermissionRepository.findByRoleMark(roleMark);
    }

    public Flux<AuthPermission> findByRoleMarks(List<String> roleMarks) {
        return authRolePermissionRepository.findByRoleMarks(roleMarks);
    }

    public Flux<AuthRolePermission> save(String roleMark, List<String> permissionMarks) {
        if (permissionMarks == null || permissionMarks.isEmpty()) {
            return Flux.empty();
        }
        List<AuthRolePermission> list = permissionMarks.stream().map(permissionMark -> new AuthRolePermission().setPermissionMark(permissionMark).setRoleMark(roleMark)).toList();
        return authRolePermissionRepository.deleteByRoleMark(roleMark)
                .flatMapMany(k->authRolePermissionRepository.saveAll(list));
    }

    public Mono<Long> deleteByRoleMark(String roleMark) {
        return authRolePermissionRepository.deleteByRoleMark(roleMark);
    }
}